// pages/index/my/entrycertificate/index.js
import Wxml2Canvas from 'wxml2canvas'
import { getmembermatchcard,uploadmatchcardpic,checkmatchcardupload } from "../../../http/match";
import { upload } from '../../../utils/upload'
import { getAuth ,getUrl} from '../../../utils/account'
const app = getApp();

Page({
  
  /**
   * 页面的初始数据
   */

  data: {
    staticUrl: app.globalData.staticUrl,
    frameClass1: 'z1', //默认正面在上面
    frameClass2: 'z2',
    matchcard:{
    /* 'title':'电子参赛证',
      'color':'#138140',
      'bgurl':'https://shanggaolian.scoringchina.com/60/55b87015a038b7ac74e3db2f24622e.png',
      'matchtitle':'2023中国商学院校友高尔夫联盟第三届“联盟杯”大师赛',
      'matchcourse':'横店禹山高尔夫球场',
      'matchdate':'2023-04-18~19',
      'playername':'黄国典',
      'playeraccademy':'中欧国际工商学院',
      'playeraccademylogourl':'https://lianmeng.scoringchina.com/upload/e3/f526589f9221ec90f1c702f92b0b0f.jpg',
      'playerbiourl':'https://lianmeng.scoringchina.com/storage/topic/20220711/85b8308592e2f5991caab7f0bf3a42a4.jpg',
      'playerqrcode':'https://shanggaolian.scoringchina.com/5c/3217d4a0a85a06090df95f1e7279a5.png',
      'desctitle':'鸣 谢',
      'sponsorsurl':'https://shanggaolian.scoringchina.com/79/2082a1a84ed1652521dfc200f2fbfa.png',*/
    },
    userInfo:"",
    mt_id:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log(app.globalData.userInfo);
    if (app.globalData.userInfo.openid && app.globalData.userInfo.session_key) {

      console.log(app.globalData.userInfo);
      this.setData({
        islogin: true
      })
    }

    if (!this.data.islogin && wx.getStorageSync('autoreg') == "1") {
      var that = this;
      app.wxlogin(app, function () {

        that.setData({
          islogin: true
        });
        that.onShow();
      });
      return;
    }

    if (!this.data.islogin) {
     
 var url =  '../../login/login?url='+this.getCurrentPageUrl();
     wx.redirectTo({
       url:url,
     })
      return;
    }
    var userInfo = app.globalData.userInfo;
    if (userInfo != undefined && userInfo != null) {
      this.setData({
        userInfo: userInfo
      });
      // var obj = this.selectComponent("#register");
      // obj.filldata(userInfo.data);
    }
      const { mt_id } = options
      if(mt_id){
      this.setData({mt_id});
      }
      this.getmatchcard();
    

    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    var userInfo = app.globalData.userInfo;
    if (userInfo != undefined && userInfo != null) {
      this.setData({
        userInfo: userInfo
      });
      // var obj = this.selectComponent("#register");
      // obj.filldata(userInfo.data);
    }
    var that = this;
    if (!userInfo) {
       
        wx.showModal({
            title: '提示',
            content: '尚未注册信息，请先注册信息',
            success: res => {
                if (res.confirm) {
                    wx.navigateTo({
                        url: '/pages/More/information',
                    })
                }
                if(res.cancel){
                  that.goback();
                }
            }
        })
    } else {
    
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

 

  getCurrentPageUrl(){
    var pages = getCurrentPages()    //获取加载的页面
    var currentPage = pages[pages.length-1]    //获取当前页面的对象
    var url = currentPage.route    //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    var urlWithArgs = url + '?'
    for(var key in options){
    var value = options[key]
    urlWithArgs += key + '=' + value + '&'
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length-1)
    return urlWithArgs
  },


  rotateFn: function(e) {
    var that = this
    if (this.data.frameClass1 == 'z1' &&
        this.data.frameClass2 == 'z2') {
        that.setData({
            frameClass1: "front",
            frameClass2: "back",
        })
        setTimeout(function() {
            that.setData({
                frameClass1: "z2",
                frameClass2: "z1",
            })
        }, 1000);
    } else {
        that.setData({
            frameClass1: "back",
            frameClass2: "front",
        })
        setTimeout(function() {
            that.setData({
                frameClass1: "z1",
                frameClass2: "z2",
            })
        }, 1000);
    }
},
drawMyCanvas() {

  if(this.data.isdraw){
    return;
  }
  wx.showLoading();
  this.setData({isdraw:true});
  const that = this
  const query = wx.createSelectorQuery().in(this);
  query.select('#my-canvas').fields({ // 选择需要生成canvas的范围
      size: true,
      scrollOffset: true
  }, data => {
      let width = data.width;
      let height = data.height;
      that.setData({
          width,
          height
      })
      setTimeout(() => {
          that.startDraw()
      }, 1500);
 }).exec()
},
startDraw() {
  let that = this
   
  // 创建wxml2canvas对象
  let drawMyImage = new Wxml2Canvas({
    element: 'myCanvas', // canvas的id,
    obj: that, // 传入当前组件的this
    width: that.data.width * 2,
    height: that.data.height * 2,
    background: 'transparent', // 生成图片的背景色
    progress(percent) { // 进度
      // console.log(percent);
    },
    finish(url) { // 生成的图片
      wx.hideLoading()
      that.savePoster(url);
      
    },
    error(res) { // 失败原因
      console.log(res);
      wx.hideLoading()
      that.setData({isdraw:false});
    }
  }, this);
  let data = {
      // 获取wxml数据
      list: [{
          type: 'wxml',
          class: '.my_canvas .my_draw_canvas',  // my_canvas要绘制的wxml元素根类名， my_draw_canvas单个元素的类名（所有要绘制的单个元素都要添加该类名）
          limit: '.my_canvas', // 要绘制的wxml元素根类名
          x: 0,
          y: 0
      }]
  }
  // 绘制canvas
  drawMyImage.draw(data, this);
},
savePoster(url) {
  const that = this
  wx.saveImageToPhotosAlbum({
      filePath:url,
      finish:function(){
        
      },
      success: function() {
          wx.showToast({
              title: '保存成功',
              icon: 'none',
              duration: 1500
          });
          that.setData({isdraw:false});
      },
      fail(err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      wx.saveImageToPhotosAlbum({
                          filePath: that.data.imgUrl,
                          success: function () {

                            wx.showToast({
                              title: '保存成功',
                              icon: 'success',
                              duration: 2000
                            })
                            that.setData({isdraw:false});
                          },
                      })
                  } else {
                      wx.showToast({
                          title: '授权失败，请稍后重新获取',
                          icon: 'none',
                          duration: 1500
                      });
                      that.setData({isdraw:false});
                  }
                }
              })
            }
          })
        }

        that.setData({isdraw:false});
      }
    })
},

getmatchcard(){
  var {matchcard} = this.data 
  var that = this;
  wx.showLoading({
    title: '获取证件',
  })
  getmembermatchcard({ player_id: this.data.userInfo.player_id,mt_id: this.data.mt_id }).then(res => {
    if(res.data){
      matchcard = res.data;
      that.setData({matchcard});
      that.initcard();
      wx.hideLoading();
    }
    else{
      that.goback();
    }
})
},

controlSearchShow:function (){
  wx.navigateTo({
    url: '/pages//More/registerlists/registerlists',
  })
},

goback:function(){
  const pages = getCurrentPages() //获取加载的页面
  if(pages.length<=1){
    wx.switchTab({
      url: '/pages/index/index',
    })
  }
  else{
    wx.navigateBack({
      delta: -1,
    })
  }
},

 initcard(){
  var matchcard = this.data.matchcard;
  var that = this;
  var countpic = 0;
  for (let key in  matchcard) {
   
    if(key.indexOf('url')>0 && matchcard[key] ){
      console.log( matchcard[key]);
      countpic ++;
        wx.downloadFile({
          url: matchcard[key],
          success:function(res){
            matchcard[key] = res.tempFilePath;
          },
          complete:function(){
            countpic--;
            if(countpic ==0){
              console.log( matchcard);
              that.setData({
                matchcard : matchcard,
              })
            }
          }
        })
    }
}
 },
 gocenter:function(){
    wx.switchTab({
      url: '/pages/index/my/mypage/mypage',
    })
 },
   // 上传参赛证件
  async uploadImg() {
    var that = this;
      var sn_id = this.data.matchcard.sn_id;
    var rescehck = await checkmatchcardupload({sn_id});
      if(rescehck.code==1){
       var url=  await upload();
        
      var urllinks = url.length ? app.globalData.host + '/storage/' + url[0]:'';
      await uploadmatchcardpic({ urllinks,sn_id }).then(res => {
        console.log(res);
        if(res.code==1){
        that.setData({
          'matchcard.playerbiourl': urllinks,
         })
        }
      })
    }

 

      
      
  },
})